<template>
  <BlocklyCompoment id="blockly1"></BlocklyCompoment>

  <BlocklyCompoment id="blockly2" :options="options" ref="foo"></BlocklyCompoment>

  <div id="simulator">
    <button v-on:click="run" v-if="!isRun">运行</button>
    <button v-on:click="reset" v-if="isRun">重置</button>
    <!-- <button v-on:click="showCode" type="button">Show JavaScript</button> -->
    <iframe :src="src" ref="simulator"></iframe>
  </div>

  <div id="header"></div>
  <ul id="menu">
    <li>
      <button id="backBtn" type="button" @click="goback">返回</button>
    </li>
    <li>
      <button id="saveButton" title="save" @click="saveFile">保存</button>
    </li>
    <li>
      <button id="importButton" @click="openFile">导入</button>
    </li>
  </ul>
  <input type="file" id="fileElem" accept=".xml" style="display: none;" />
  <h1>Edit</h1>
</template>

<script lang="ts">
import { ref, defineComponent, onMounted } from 'vue'
import BlocklyCompoment from './BlocklyCompoment.vue'
import BlocklyJS from 'blockly/javascript'
import Blockly from 'blockly'
import axios from 'axios'

const port = 3000;

export default defineComponent({
  name: 'Edit',
  components: {
    BlocklyCompoment
  },
  data() {
    return {
      isRun: false,
      btnLabel: '运行',
      code: '',
      src: `http://localhost:${port}/simulator/index3.html`,
      options: {
        media: 'media/',
        grid:
        {
          spacing: 25,
          length: 3,
          colour: '#ccc',
          snap: true
        },
        toolbox:
          `<xml>
          <category name="Logic" colour="%{BKY_LOGIC_HUE}">
            <block type="controls_if"></block>
            <block type="logic_compare"></block>
            <block type="logic_operation"></block>
            <block type="logic_negate"></block>
            <block type="logic_boolean"></block>
            <block type="logic_null" disabled="true"></block>
            <block type="logic_ternary"></block>
          </category>
          <category name="Loops" categorystyle="loop_category">
      <block type="controls_repeat_ext">
        <value name="TIMES">
          <shadow type="math_number">
            <field name="NUM">10</field>
          </shadow>
        </value>
      </block>
      <block type="controls_repeat" disabled="true"></block>
      <block type="controls_whileUntil"></block>
      <block type="controls_for">
        <value name="FROM">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
        <value name="TO">
          <shadow type="math_number">
            <field name="NUM">10</field>
          </shadow>
        </value>
        <value name="BY">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
      </block>
      <block type="controls_forEach"></block>
      <block type="controls_flow_statements"></block>
    </category>
    <category name="Math" categorystyle="math_category">
      <block type="math_number" gap="32">
        <field name="NUM">123</field>
      </block>
      <block type="math_arithmetic">
        <value name="A">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
        <value name="B">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
      </block>
      <block type="math_single">
        <value name="NUM">
          <shadow type="math_number">
            <field name="NUM">9</field>
          </shadow>
        </value>
      </block>
      <block type="math_trig">
        <value name="NUM">
          <shadow type="math_number">
            <field name="NUM">45</field>
          </shadow>
        </value>
      </block>
      <block type="math_constant"></block>
      <block type="math_number_property">
        <value name="NUMBER_TO_CHECK">
          <shadow type="math_number">
            <field name="NUM">0</field>
          </shadow>
        </value>
      </block>
      <block type="math_round">
        <value name="NUM">
          <shadow type="math_number">
            <field name="NUM">3.1</field>
          </shadow>
        </value>
      </block>
      <block type="math_on_list"></block>
      <block type="math_modulo">
        <value name="DIVIDEND">
          <shadow type="math_number">
            <field name="NUM">64</field>
          </shadow>
        </value>
        <value name="DIVISOR">
          <shadow type="math_number">
            <field name="NUM">10</field>
          </shadow>
        </value>
      </block>
      <block type="math_constrain">
        <value name="VALUE">
          <shadow type="math_number">
            <field name="NUM">50</field>
          </shadow>
        </value>
        <value name="LOW">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
        <value name="HIGH">
          <shadow type="math_number">
            <field name="NUM">100</field>
          </shadow>
        </value>
      </block>
      <block type="math_random_int">
        <value name="FROM">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
        <value name="TO">
          <shadow type="math_number">
            <field name="NUM">100</field>
          </shadow>
        </value>
      </block>
      <block type="math_random_float"></block>
      <block type="math_atan2">
        <value name="X">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
        <value name="Y">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
      </block>
    </category>
    <category name="Text" categorystyle="text_category">
      <block type="text"></block>
      <block type="text_multiline"></block>
      <block type="text_join"></block>
      <block type="text_append">
        <value name="TEXT">
          <shadow type="text"></shadow>
        </value>
      </block>
      <block type="text_length">
        <value name="VALUE">
          <shadow type="text">
            <field name="TEXT">abc</field>
          </shadow>
        </value>
      </block>
      <block type="text_isEmpty">
        <value name="VALUE">
          <shadow type="text">
            <field name="TEXT"></field>
          </shadow>
        </value>
      </block>
      <block type="text_indexOf">
        <value name="VALUE">
          <block type="variables_get">
            <field name="VAR">text</field>
          </block>
        </value>
        <value name="FIND">
          <shadow type="text">
            <field name="TEXT">abc</field>
          </shadow>
        </value>
      </block>
      <block type="text_charAt">
        <value name="VALUE">
          <block type="variables_get">
            <field name="VAR">text</field>
          </block>
        </value>
      </block>
      <block type="text_getSubstring">
        <value name="STRING">
          <block type="variables_get">
            <field name="VAR">text</field>
          </block>
        </value>
      </block>
      <block type="text_changeCase">
        <value name="TEXT">
          <shadow type="text">
            <field name="TEXT">abc</field>
          </shadow>
        </value>
      </block>
      <block type="text_trim">
        <value name="TEXT">
          <shadow type="text">
            <field name="TEXT">abc</field>
          </shadow>
        </value>
      </block>
      <block type="text_count">
        <value name="SUB">
          <shadow type="text"></shadow>
        </value>
        <value name="TEXT">
          <shadow type="text"></shadow>
        </value>
      </block>
      <block type="text_replace">
        <value name="FROM">
          <shadow type="text"></shadow>
        </value>
        <value name="TO">
          <shadow type="text"></shadow>
        </value>
        <value name="TEXT">
          <shadow type="text"></shadow>
        </value>
      </block>
      <block type="text_reverse">
        <value name="TEXT">
          <shadow type="text"></shadow>
        </value>
      </block>
      <label text="Input/Output:" web-class="ioLabel"></label>
      <block type="text_print">
        <value name="TEXT">
          <shadow type="text">
            <field name="TEXT">abc</field>
          </shadow>
        </value>
      </block>
      <block type="text_prompt_ext">
        <value name="TEXT">
          <shadow type="text">
            <field name="TEXT">abc</field>
          </shadow>
        </value>
      </block>
    </category>
    <category name="Lists" categorystyle="list_category">
      <block type="lists_create_with">
        <mutation items="0"></mutation>
      </block>
      <block type="lists_create_with"></block>
      <block type="lists_repeat">
        <value name="NUM">
          <shadow type="math_number">
            <field name="NUM">5</field>
          </shadow>
        </value>
      </block>
      <block type="lists_length"></block>
      <block type="lists_isEmpty"></block>
      <block type="lists_indexOf">
        <value name="VALUE">
          <block type="variables_get">
            <field name="VAR">list</field>
          </block>
        </value>
      </block>
      <block type="lists_getIndex">
        <value name="VALUE">
          <block type="variables_get">
            <field name="VAR">list</field>
          </block>
        </value>
      </block>
      <block type="lists_setIndex">
        <value name="LIST">
          <block type="variables_get">
            <field name="VAR">list</field>
          </block>
        </value>
      </block>
      <block type="lists_getSublist">
        <value name="LIST">
          <block type="variables_get">
            <field name="VAR">list</field>
          </block>
        </value>
      </block>
      <block type="lists_split">
        <value name="DELIM">
          <shadow type="text">
            <field name="TEXT">,</field>
          </shadow>
        </value>
      </block>
      <block type="lists_sort"></block>
      <block type="lists_reverse"></block>
    </category>
    <category name="Colour" categorystyle="colour_category">
      <block type="colour_picker"></block>
      <block type="colour_random"></block>
      <block type="colour_rgb">
        <value name="RED">
          <shadow type="math_number">
            <field name="NUM">100</field>
          </shadow>
        </value>
        <value name="GREEN">
          <shadow type="math_number">
            <field name="NUM">50</field>
          </shadow>
        </value>
        <value name="BLUE">
          <shadow type="math_number">
            <field name="NUM">0</field>
          </shadow>
        </value>
      </block>
      <block type="colour_blend">
        <value name="COLOUR1">
          <shadow type="colour_picker">
            <field name="COLOUR">#ff0000</field>
          </shadow>
        </value>
        <value name="COLOUR2">
          <shadow type="colour_picker">
            <field name="COLOUR">#3333ff</field>
          </shadow>
        </value>
        <value name="RATIO">
          <shadow type="math_number">
            <field name="NUM">0.5</field>
          </shadow>
        </value>
      </block>
    </category>
    <sep></sep>
    <category name="Variables" categorystyle="variable_category" custom="VARIABLE"></category>
    <category name="Functions" categorystyle="procedure_category" custom="PROCEDURE"></category>
        </xml>`
      }
    }
  },
  methods: {
    simulate(data: any) {
      const simulator = (<any>this.$refs.simulator).contentWindow;
      if (simulator) {
        simulator.postMessage(data, "*");
      }
    },
    goback() {
      this.$router.back();
    },
    showCode() {
      console.log(BlocklyJS.workspaceToCode((<any>this.$refs["foo"]).workspace));
    },
    run() {
      if (this.$data.isRun) return;
      this.$data.isRun = true;

      let code = BlocklyJS.workspaceToCode((<any>this.$refs["foo"]).workspace);
      try {
        const result = eval(code);
        if (result.length >= 3) {
          const index = ['传统模式', '智能模式'].indexOf(result[0]);
          if (index != -1) {
            this.simulate({
              cmd: 'run',
              param: {
                isAi: index == 1,
                redDuration: result[1],
                greenDuration: result[2]
              }
            });
            return;
          }
        }
        this.$data.isRun = false;
        window.alert('运行失败');
      } catch (err) {
        this.$data.isRun = false;
        window.alert('运行失败');
      }
    },
    saveFile() {
      var xml = Blockly.Xml.workspaceToDom(Blockly.getMainWorkspace());
      var code = Blockly.Xml.domToPrettyText(xml);
      var blob = new Blob([code], {
        type: 'text/xml'
      });
      var src = URL.createObjectURL(blob);
      var link = document.createElement('a');

      link.download = 'proj-1.xml';
      link.style.display = 'none';
      link.href = src;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    openFile() {
      var fileElem = document.getElementById("fileElem");
      if (fileElem) {
        fileElem.onchange = function () {
          let files = fileElem && (<any>fileElem)['files'];
          if (files && files.length > 0) {
            var reader = new FileReader;
            reader.readAsText(files[0]);
            reader.onload = function (e) {
              var text = this.result;
              var xml;
              try {
                xml = Blockly.Xml.textToDom(text as string);
              } catch (e) {
                alert('导入失败')
                return;
              }

              Blockly.Xml.appendDomToWorkspace(xml, Blockly.getMainWorkspace())
            }
          }
        };
        fileElem.click();
      }

    },
    reset() {
      this.simulate({
        cmd: 'reset',
        param: {}
      });
      this.$data.isRun = false;
    }
  },
  setup() {

    onMounted(() => {
      axios.get(`http://localhost:${port}/tutorial/traffic-light.xml`)
        .then(response => {
          var xmlText = response.data;
          try {
            let xml = Blockly.Xml.textToDom(xmlText as string);
            Blockly.Xml.appendDomToWorkspace(xml, Blockly.getMainWorkspace())
          } catch (e) {
          }
        });
    })

  }
}
)
</script>

<style scoped>
#header {
  width: 100%;
  height: 6%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(0, 255, 242, 0.63);
}

#menu {
  right: 20px;
  top: 10px;
  position: absolute;
  /* margin: 50px auto; */
}

#menu li {
  text-decoration: none; /*去掉前面的圆点*/
  list-style: none;
  float: left;
  margin: 5px;
}

#header span {
  font-size: 30pt;
  left: 2%;
  position: absolute;
}

#simulator {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 50%;
  height: 94%;
  margin: 0;
  background-color: beige;
}

#simulator iframe {
  width: 98%;
  height: 95%;
  position: absolute;
  bottom: 2%;
  left: 1%;
  border-style: none;
}

#blockly1 {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 50%;
  height: 94%;
}

#blockly2 {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 50%;
  height: 94%;
}
</style>
